package com.atguigu.gmall.product.service.impl;


import com.atguigu.gmall.model.product.SpuImage;
import com.atguigu.gmall.model.product.SpuInfo;
import com.atguigu.gmall.model.product.SpuSaleAttr;
import com.atguigu.gmall.model.product.SpuSaleAttrValue;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.BaseSpuInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author Dell
* @description 针对表【spu_info(商品表)】的数据库操作Service实现
* @createDate 2022-05-18 19:40:48
*/
@Service
public class BaseSpuInfoServiceImpl extends ServiceImpl<BaseSpuInfoMapper, SpuInfo>
implements BaseSpuInfoService {

    @Autowired
    private BaseSpuImageMapper spuImageMapper;

    @Autowired
    private BaseSpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private BaseSpuSaleAttrValueMapper saleAttrValueMapper;

    @Override
    public Page<SpuInfo> getSpuListPage(Long page, Long limit, Long category3Id) {
        Page<SpuInfo> infoPage = new Page<>(page,limit);
        QueryWrapper<SpuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category3_id",category3Id);
        return baseMapper.selectPage(infoPage,queryWrapper);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1、保存商品
        baseMapper.insert(spuInfo);
        //2、保存商品图片
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        for (SpuImage image : spuImageList) {
            SpuImage spuImage = new SpuImage();
            spuImage.setSpuId(spuInfo.getId());
            spuImage.setImgName(image.getImgName());
            spuImage.setImgUrl(image.getImgUrl());
            spuImageMapper.insert(spuImage);
        }
        //3、保存spu销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
            spuSaleAttr.setSpuId(spuInfo.getId());
            //新增spu销售属性
            spuSaleAttrMapper.insert(spuSaleAttr);
            List<SpuSaleAttrValue> attrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            for (SpuSaleAttrValue attrValue : attrValueList) {
                attrValue.setSpuId(spuInfo.getId());
                attrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                //新增spu销售属性值
                saleAttrValueMapper.insert(attrValue);
            }
        }
    }
}
